package com.example.video.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 设备id编码，测试环境中的设备id是ip加端口，导致id文件保存失败，故对设备id进行编码。
 * 通过字符映射实现。
 */
public class DeviceEncode {
    private static final Map<Character, Character> encodeMap = new HashMap<>();
    private static final Map<Character, Character> decodeMap = new HashMap<>();

    static {
        // 定义字符映射
        String originalChars = "0123456789:.";
        String replacementChars = "ABCDEFGHIJKL";

        for (int i = 0; i < originalChars.length(); i++) {
            encodeMap.put(originalChars.charAt(i), replacementChars.charAt(i));
            decodeMap.put(replacementChars.charAt(i), originalChars.charAt(i));
        }
    }

    public static void main(String[] args) {
        // 原始文件名
        String originalFileName = "qweqwe";
        // 替换后的文件名
        String modifiedFileName = encodeFileName(originalFileName);
        // 恢复后的文件名
        String restoredFileName = decodeFileName(modifiedFileName);

        System.out.println("Original file name: " + originalFileName);
        System.out.println("Modified file name: " + modifiedFileName);
        System.out.println("Restored file name: " + restoredFileName);

        // 示例：重命名文件（假设文件在当前工作目录）
        // File originalFile = new File(originalFileName);
        // File modifiedFile = new File(modifiedFileName);
        // if (originalFile.renameTo(modifiedFile)) {
        //     System.out.println("File renamed successfully.");
        // } else {
        //     System.out.println("Failed to rename file.");
        // }
    }

    // 使用自定义字符映射编码文件名
    public static String encodeFileName(String fileName) {
        StringBuilder encoded = new StringBuilder();
        for (char c : fileName.toCharArray()) {
            encoded.append(encodeMap.getOrDefault(c, c));
        }
        return encoded.toString();
    }

    // 使用自定义字符映射解码文件名
    public static String decodeFileName(String encodedFileName) {
        StringBuilder decoded = new StringBuilder();
        for (char c : encodedFileName.toCharArray()) {
            decoded.append(decodeMap.getOrDefault(c, c));
        }
        return decoded.toString();
    }
}
